(function() {

	angular.module('cf-content')

	.directive('market', ['$timeout', "$window", function($timeout, $window, EVENT) {
			return {
				restrict: 'AE',
				templateUrl: 'app/page/marketmanage/marketmanage.html',
				// replace:true,
				controller: marketmanage,
				controllerAs: 'marketCtrl'
			}
		}])
		.controller('MarketModalInstanceCtrl', MarketModalInstanceCtrl)

	MarketModalInstanceCtrl.$inject = ['$scope', '$uibModalInstance'];

	function MarketModalInstanceCtrl($scope, $uibModalInstance) {


		$scope.ok = function() {
			$uibModalInstance.close(true);
		};

		$scope.cancel = function() {
			$uibModalInstance.dismiss(false);
		};
	}

	marketmanage.$inject = ['$scope', '$uibModal','$q','$timeout', 'Api'];

	function marketmanage($scope, $uibModal,$q,$timeout,Api) {
		var vm = this;
		vm.area = {
			provinceList: [],
			cityList: [],
			countyList: []
		}
		vm.showOperationButton=false;
		//pagination
		vm.pagination={
			max_size:5,
			page_size:20,
			page_no:1,
			total_item:2
		}
		//model
		vm.EnsureModel = function openModel(size, item, callback) {
			var modalInstance = $uibModal.open({
				animation: true,
				templateUrl: 'EnsureModel',
				controller: 'EnsureModelCtrl',
				size: size,
				resolve: {
					item: function() {
						return '删除'+item;
					}
				}
			});

			modalInstance.result.then(callback);
		}

		vm.InfoModel = function openModel(size, info,type,callback) {
				var modalInstance = $uibModal.open({
					animation: true,
					templateUrl: 'InfoModel',
					controller: 'InfoModelCtrl',
					size: size,
					resolve: {
						info: function() {
							return info;
						},
						type:function(){
							return type;
						}
					}
				});

				modalInstance.result.then(callback);
		}

		QueryMrketList();

		vm.GetCityList=function(market,id) {
			console.log(market,id)
				Api.Area.CityQuery({
					type: 1,
					province_id: id
				}).$promise.then(function(data) {
					var reset=true;
					market['cityList'] = data.data;
					for (var i in market['cityList']){
						if(market['cityList'][i].id==market.city_id){
							reset=false;
							break;
						}
					}
					if(reset){
						market.city_id=market['cityList'][0].id;
					}
					vm.GetCountyList(market,market.city_id)

				})
		}

		vm.GetCountyList=function(market,id) {
				Api.Area.CountyQuery({
					city_id: id
				}).$promise.then(function(data) {
					var reset=true;
					market['countyList'] = data.data;
					for (var i in market['countyList']){
						if(market['countyList'][i].id==market.county_id){
							reset=false;
							break;
						}
					}
					if(reset){
						market.county_id=market['countyList'][0].id;
					}
				})
		}

		vm.GetProvinceList=function(market) {
			Api.Area.ProvinceQuery({
				shown: true
			}).$promise.then(function(data) {
				market['provinceList'] = data.data;
				if(!market.province_id){
					market.province_id=market['provinceList'][0].id;
				}
				vm.GetCityList(market,market.province_id)
			})
		}

		function QueryMrketList() {
			Api.Market.Query({page_size:vm.pagination.page_size,page_no:vm.pagination.page_no}).$promise.then(function(data) {
				if(data.code!=0)
					vm.InfoModel('sm','加载失败','error')
				vm.pagination.total_item=data.data.total_item;
				vm.markets = data.data.market_list;
				angular.forEach(vm.markets, function(value) {
					value['$selected'] = false;
				})
			})
		}
		vm.showAreaName=function(market,type){
			if(type==0){
				if(market.province_name)
					return market.province_name;
				for(var i in market.provinceList){
					if(market.provinceList[i].id==market.province_id)
						return market.provinceList[i].name;
				}
			}
			else if(type==1){
				if(market.city_name)
					return market.city_name;
				for(var i in market.cityList){
					if(market.cityList[i].id==market.city_id)
						return market.cityList[i].name;
				}
			}
			else if(type==2){
				if(market.county_name)
					return market.county_name;
				for(var i in market.countyList){
					if(market.countyList[i].id==market.county_id)
						return market.countyList[i].name;
				}
			}
		}

		vm.paginationChange=function(){
			QueryMrketList();
		}


		vm.resetFilter = function(data) {
			$scope.marketFilter = '';
		}

		

		vm.addMarket = function() {
			vm.inserted = {
				$selected: false,
				contact: '',
				county_id: '',
				province_id: '',
				city_id: '',
				detail_address: '',
				market_name: '',
			};
			vm.markets.push(vm.inserted);
		};
		vm.toggleAllCheckbox = function() {
			angular.forEach(vm.markets, function(value) {
				value['$selected'] = vm.toggleCheckbox;
			})
			if(!vm.toggleCheckbox){
              vm.showOperationButton=false;
            }
		}
		vm.showOperation=function(data){
            for(var i in vm.markets){
                if(vm.markets[i].$selected){
                    vm.showOperationButton=true;
                    return;
                }
            }
            vm.toggleCheckbox=false;
            vm.showOperationButton=false;
        }
		vm.deleteAll=function(){
            var selectedArray=[],promiseList=[];
            for(var i in vm.markets){
                if(vm.markets[i].$selected){
                    selectedArray.push(vm.markets[i].market_id);
                }
            }
            if(selectedArray.length<1){
                vm.InfoModel('sm','请选择要操作的项')
            }
            else{
                vm.EnsureModel('sm','选中项',function(data){
                    for(var j in selectedArray){
                        promiseList.push(Api.Market.Delete({market_id:selectedArray[j]}).$promise)
                    }
                    $q.all(promiseList).then(function(data){
                        QueryMrketList()
                        if(data.code==0){
                        	vm.InfoModel('sm','操作成功','success');
                        }
                        else{
                        	vm.InfoModel('sm','操作失败','error');
                        }
                    })
                })
                
            }
        }
		vm.saveMarket = function(data, id) {
			if (!!id) {
				Api.Market.Update(angular.extend({},data,{market_id:id})).$promise.then(function(data) {
					QueryMrketList()
				})
			} else {
				Api.Market.Put(data).$promise.then(function(data) {
					QueryMrketList()
				})
			}
		}

		vm.checkData = function(data) {
			if (!data) {
				return '内容不能为空';
			}
		}

		vm.checkPhone=function(data){
			
			var patt = /^1\d{10}$/;
			if(!patt.test(data)){
				return '联系方式格式不正确'
			}
			if(!data){
				return '内容不能为空'
			}
		}
		
		vm.removeMarket = function(id,obj) {
			vm.EnsureModel('sm',obj.market_name, function(data) {
				if (data) {
					Api.Market.Delete({market_id:obj.market_id}).$promise.then(function(data){
						if(data.code==0)
							vm.InfoModel('sm','操作成功','success')
						else
							vm.InfoModel('sm','操作失败','error')

					})
					vm.markets.splice(id, 1)
				}
			})
		}

		// cancel all changes
		vm.cancel = function(rowform,reset) {
			rowform.$cancel();
			if(reset)
				vm.markets.pop();
		};

		
	}

})();